<?php
	class xw {
		function sendJson($params) {
			/*
			 * Summary: Sends a Json encoded response to the client.
			 * @param  array $params An array of strings to be encoded as json.
			 * @return bool          Always true. 
			 */
				echo(json_encode($params));
				return(true);
		}
		
		function registerUser($username, $email, $password) {
			
			//Make sure the username isn't empty
			if(empty($username)) 
			{ 
				$problems[] = 'username_empty';
			}
			
			//Make sure the username is > 4 and < 12 characters
			
			if(strlen($username) < 4 || strlen($username) > 12)
			{
				$problems[] = 'username_too_long';
			}
			
			//Make sure the username
			
			//Make sure the password is > 4 characters
			
			
			
		}

		
		function analyseAndInit($version, $clientEmail, $authcode) {
			/*
			 * Summary: Analyses version number and client email and starts the session (if it's all OK)
			 * @param  int    $version	   Version number of client
			 * @param  string $clientEmail Email address of client
			 * @param  string $authcode    Secret code the  client has to authenticate
			 * @return bool  			   Validity of client handshake
			 */			
			 
			//Validate our email
			$emailValid = xw::validateEmail($clientEmail);
			
			//Check the version number is valid
			if($version == SYSTEM_CLIENT_VERSION) {
				$versionValid = true;
			}
			
			//Check they're both valid
			if($versionValid && $emailValid) {
				//Now start the session (or try to)
				
				//Check if the user is registered, and get the ID
				$id = xw::userIsRegistered($clientEmail, $authcode);
				
				//If we're not registered ..
				if(!$id) {
					xw::sendResult(false, 'client_not_registered_or_wrong_details');
				} else {
					//OH YAY!
					
					//Right, now we have to check that the session is all OK
					$session = xw::getLogId();
					
					if($session) {
						//We're in!
						
						//Now populate the session variables with data from the DB
						
						$res = mysql_query('SELECT * FROM `users` WHERE id = "' . $id .'";') or die(mysql_error());
						
						
						$row = mysql_fetch_assoc($res);
						
						
						$_SESSION['user_id'] = $row['id'];
						$_SESSION['user_email'] = $row['email'];
						$_SESSION['user_rank'] = $row['rank'];
						$_SESSION['user_banned'] = $row['banned'];
						$_SESSION['user_username'] = $row['username'];
						
						if($_SESSION['user_banned'] == false) {
							//We're not banned! Send the OK!
							$remoteIP = $_SERVER['REMOTE_ADDR'];
							$sql = "UPDATE `users` SET `last_known_ip` = '$remoteIP' WHERE `users`.`id` = " . $_SESSION['user_id'] . " LIMIT 1;";
							mysql_query($sql) or die(mysql_error());
							xw::sendResult(true, 'ok');
						} else {
							//Oh gawd.
							xw::sendResult(false, 'banned');
						}
						
					} else {
						//Session already started :(
						xw::sendResult(false, 'session_already_started');
					}
					
					
				}
			} elseif ($versionValid && !$emailValid) {
				//It's an invalid email
				xw::sendResult(false, 'invalid_email');
			} else {
				//Invalid version
				xw::sendResult(false, 'invalid_version');
			}
		}
		
		function getServiceStatusArray() {
			/*
			 * Summary: Fetches the service status array to be displayed to the client
			 * @return  array				All the stuff that needs to get to the client
			 */	
			 
			$serviceStatusArray;
			 
			//Alrighto! Let's start off by pulling all the stuff in from the DB and putting them into the correct arrays
			 
			 
			$online = mysql_query('SELECT * from `settings` WHERE setting = "status";') or die(mysql_error());
			$maintMsg = mysql_query('SELECT * from `settings` WHERE setting = "maintenance_msg";') or die(mysql_error());
			$motd = mysql_query('SELECT * FROM `motd` ORDER BY date ASC LIMIT 1;') or die(mysql_error());
			$clientVer = mysql_query('SELECT * from `settings` WHERE setting = "latest_client_version";') or die(mysql_error());
			
			$onlineA = mysql_fetch_assoc($online);
			$maintMsgA = mysql_fetch_assoc($maintMsg);
			$motdA = mysql_fetch_assoc($motd);
			$clientVerA = mysql_fetch_assoc($clientVer);
			
			//Stick the service status in
			$serviceStatusArray['status'] = $onlineA['value'];
			
			
			if($onlineA['value'] == 'maintenance') {
				//Stick the maintenance msg in if we're in maintenance mode
				$serviceStatusArray['maint_msg'] = $maintMsgA['value'];
			}
			
			//Stick the MOTD in
			$serviceStatusArray['motd'] = array($motdA['text'], $motdA['date']);
			
			//Shove in the latest version
			$serviceStatusArray['latest_client_version'] = $clientVerA['value'];

			//var_dump($serviceStatusArray);
			
			return($serviceStatusArray);
		}
		
		function userIsRegistered($email, $authcodeOrPass) {
			/*
			 * Summary: Returns whether or not the user has an account, based on authentication information provided.
			 * @param	string	Email			Email address of the client
			 * @param	string	Authcode/Pass	Can be either.
			 * @return  mixed					User's ID or false
			 */	
			
			$email = mysql_real_escape_string($email);
			$authcodeOrPass = mysql_real_escape_string($authcodeOrPass);
			
			$sql = 'SELECT * FROM `users` WHERE email = "' . $email . '" AND ((password = "' . $authcodeOrPass .'") OR (authcode = "' . $authcodeOrPass . '"));';
			
			$res = mysql_query($sql) or die(mysql_error());
			
			$row = mysql_fetch_assoc($res);
			
			$count = mysql_num_rows($res);
			
			if($count == 1) {
				return $row['id'];
			} else {
				return false;
			}

		}
		
		function dropSession() {
			/*
			 * Summary: Drops the current session
			 * @return 		true
			 */	
			session_destroy();
			xw::sendResult(true, 'dropped');
			return true;
		}
		
		function getLogId() {
			/*
			 * Summary: Returns whether or not we're logging. If true, gives the log id.
			 * @return mixed	Returns a string of the logid if we're logging, returns a false bool if we're not.
			 */	
			 
			//Make sure our log id is empty. if it's not, we're already logging and need to abort.
			if(empty($_SESSION['logid'])) {
				$_SESSION['logid'] = date('dmyHi') . '-' . uniqid();
				return($_SESSION['logid']);
			} else {
				return(false);
			}

		}

		
		function validateEmail($email) {
			/*
			 * Summary: Returns whether an email is valid
			 * @param  string $email 	Email address to check
			 * @return bool  			Validity of email
			 */
				$isValid = eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email) ? true : false;
				return($isValid);
			}

		function logChat($left, $right) {
			/*
			 * Summary: Logs the message into the database
			 * @param  string $left 	The left side of the chat
			 * @param  string $right	The right side of the chat
			 * @return bool				True/false depending on if it logs correctly
			 */	
			 
			if($_SESSION['logid']) {
				
				if(!empty($left)){ 
					xw::processLog($left, 'left');
				}
				
				if(!empty($right)) {
					xw::processLog($left, 'right');
				}
				
				
			} else {
				
			}
			
			return(true);
		}
		
		function processLog($log, $side) {
			//This function takes an array and logs it into the database

			var_dump($log);


		}
		
		function decodeClientJson($json) {
			//Simple function to decode the urlencoded json we get sent from the client.
			//Returns an array
			
			return(json_decode(stripslashes(urldecode($json))));
		}
			
		function sendResult($bool, $reason=null) {
			/*
			 * Summary: Sends a boolean to the client, with an optional message
			 * @param  bool	  $bool	 	The result to send
			 * @param  string $reason   Additional information to provide to the client
			 * @return bool				True
			 */	
			if(empty($reason)) {
				xw::sendJson(array('result'=>$bool));
			} else {
				xw::sendJson(array('result'=>$bool, 'info'=>$reason));
			}
			
			return(true);
		
		}

	}

	?>